import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
import projectTaskApi from "@/api/projectTaskApi"
import XEUtils from "xe-utils";

export default {
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      }
    },
    formData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: {
    SelectProjectTeam
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  data () {
    const defaultTime = ['09:00:00', '18:00:00']
    return {
      preFormData: {},
      testDialogVisible: false,
      saveLoading: false,
      formRules: {
        Name: [{required: true, message: '请输入标题'}],
        Acceptid: [{required: true, message: '请选择指派人'}],
        // TaskDate: [{required: true, message: '请选择预计开始时间'}],
        Status: [{required: true, message: '请选择状态'}],
        Level: [{required: true, message: '请输入优先级'}],
      },
      components: [
        {
          label: '标题',
          span: 24,
          placeholder: '请输入标题',
          prop: 'Name',
          value: 'Name',
          componentName: 'vxe-input',
        },
        {
          label: '指派人',
          span: 24,
          placeholder: '请选择指派人',
          prop: 'Acceptid',
          value: 'Acceptid',
          componentName: SelectProjectTeam,
          attrs: {}
        },
        {
          label: '反馈标题',
          span: 24,
          placeholder: '请选择反馈',
          prop: 'Testname',
          value: 'Testname',
          componentName: 'vxe-input',
          attrs: {
            readonly: true
          },
          on: {

          }
        },
        {
          label: '任务阶段',
          span: 24,
          placeholder: '请选择任务阶段',
          prop: 'Stage',
          value: 'Stage',
          componentName: 'SelectDiction',
          DictTypeCode: 'TASK_STAGE',
          exclude: []
        },
        // {
        //   label: '任务数',
        //   span: 24,
        //   placeholder: '请输入任务数',
        //   prop: 'TestName',
        //   value: 'TestName',
        //   componentName: 'vxe-input',
        //   type: 'number',
        //   attrs: {
        //     min: 0,
        //     step: 1,
        //     max:500
        //   }
        // },
        // {
        //   label: '已完成',
        //   span: 24,
        //   placeholder: '请选择指派人',
        //   prop: 'TestName',
        //   value: 'TestName',
        //   componentName: 'vxe-input',
        // },
        {
          label: '预计时间',
          span: 24,
          placeholder: '请选择',
          prop: 'TaskDate',
          value: 'TaskDate',
          componentName: 'el-date-picker',
          type: 'datetimerange',
          clearable: false,
          attrs: {
            'clearable': false,
            'range-separator': 'TO',
            'start-placeholder': '开始日期',
            'end-placeholder': '结束日期',
            'default-time': defaultTime,
            'picker-options': {}
          }
        },
        // {
        //   label: '实际开始时间和结束时间',
        //   span: 12,
        //   placeholder: '请选择',
        //   prop: 'Actual',
        //   value: 'Actual',
        //   componentName: 'el-date-picker',
        //   type: 'datetimerange',
        //   attrs: {
        //     'picker-options': {},
        //     'range-separator': 'TO',
        //     'start-placeholder': '开始日期',
        //     'end-placeholder': '结束日期',
        //     'default-time': defaultTime
        //   }
        // },
        {
          label: '优先级',
          span: 24,
          placeholder: '请输入优先级',
          prop: 'Level',
          value: 'Level',
          componentName: 'vxe-input',
          type: 'number',
          attrs: {
            min: 1,
            step: 1,
            max:500
          }
        },
        {
          label: '任务状态',
          span: 24,
          placeholder: '请选择任务状态',
          prop: 'Status',
          value: 'Status',
          componentName: 'SelectDiction',
          DictTypeCode: 'TASK_STATUS'
        },
        {
          label: '备注',
          span: 24,
          placeholder: '请输入备注',
          prop: 'Note',
          value: 'Note',
          componentName: 'vxe-textarea',
          autosize: {
            minRows: 6,
            maxRows: 6
          }
        },
      ]
    }
  },
  methods: {
    // 反馈选择
    selectData (d) {
      this.$set(this.formData, 'Testid', d.Id)
      this.$set(this.formData, 'Testname', d.Name)
      this.$set(this.formData, 'Name', `【${d.Id}】 ${d.Name}`)
      // this.formData.Testid = d.Id
      // this.formData.Testname = d.Name
      // this.formData.Name = `【${d.Id}】 ${d.Name}`// this.formData.Name || '' + d.Id;
    },
    clearP () {
      console.log('asd');
      // this.formData.Testid = ''
      // this.formData.Testname = ''
      // this.formData.Name = ''
      this.$set(this.formData, 'Testid', '')
      this.$set(this.formData, 'Testname', '')
      this.$set(this.formData, 'Name', '')
    },
    // 打开反馈
    openTest () {
      this.preFormData = {
        Projectid: this.formData.Projectid
      }
      this.testDialogVisible = true
    },
    // 保存按钮
    save() {
      if (this.formData.Projectid || this.$route.params.id) {
        // 构造开始时间、结束时间
        if (!this.formData.TaskDate) {
          this.initTaskDate()
        }
        if (this.formData.TaskDate && this.formData.TaskDate.length === 2) {
          if (typeof this.formData.TaskDate[0] === "number") {
            this.$set(this.formData, 'Started', this.formData.TaskDate[0])
            this.$set(this.formData, 'Ended', this.formData.TaskDate[1])
          } else {
            this.$set(this.formData, 'Started', this.formData.TaskDate[0].getTime())
            this.$set(this.formData, 'Ended', this.formData.TaskDate[1].getTime())
          }
        }
        // 实际开始时间、结束时间
        if (this.formData.Actual && this.formData.Actual.length === 2) {
          if (typeof this.formData.Actual[0] === "number") {
            this.$set(this.formData, 'Actualstarttime', this.formData.Actual[0])
            this.$set(this.formData, 'Actualendtime', this.formData.Actual[1])
          } else {
            this.$set(this.formData, 'Actualstarttime', this.formData.Actual[0].getTime())
            this.$set(this.formData, 'Actualendtime', this.formData.Actual[1].getTime())
          }
        }

        this.$refs.dymForm.$refs.form.validate().then((valid) => {
          let a = Object.assign(this.formData, {
            Projectid: this.formData.Projectid || this.$route.params.id,
            id: this.formData.Id,
            Classify: '2'
          })
          this.saveLoading = true
          if (this.formData.Id) {
            projectTaskApi.update(a).then(res => {
              this.$XModal.message({message: res.message, status: res.code === 1 ? 'success' : 'error'})
              if (res.code === 1) {
                this.dialogVisible = false
                // bus.$emit('showTaskByIdClose', '')
                this.$emit('close')
              }
            }).finally(() => {
              this.saveLoading = false
            })
          } else {
            projectTaskApi.create(a).then(res => {
              this.$XModal.message({message: res.message, status: res.code === 1 ? 'success' : 'error'})
              if (res.code === 1) {
                this.dialogVisible = false
                this.$emit('close')
              }
            }).finally(() => {
              this.saveLoading = false
            })
          }
        }).catch((e) => {
          this.$XModal.message({message: `表单填写错误，请检查`, status: 'error'})
        }).finally(() => this.saveLoading = false)
      } else {
        this.$XModal.message({message: '请从项目中进入', status: 'error'})
      }
    },
    // 任务弹窗
    setComponents () {
      let that = this
      if (that.formData.Projectid) {
        that.components.forEach(it => {
          if (it.prop === 'Moduleid' || it.prop === 'Acceptid') {
            this.$set(it.attrs, 'queryValue', {
              id: this.formData.Projectid
            })
          }
          if (it.prop === 'Testname') {
            it.on = Object.assign(it.on, {
              click: () => {
                that.openTest()
              },
              change (res) {
                if (res.hasOwnProperty('value')) {
                  if (!res.value) {
                    that.clearP()
                  }
                }
              }
            })
            return true
          }
          // if (it.prop === 'TaskDate' || it.prop === 'Actual') {
          //   this.$set(it.attrs, 'picker-options', {
          //     disabledDate(time) {
          //       return that.formData.PlanStarted > time.getTime();
          //     }
          //   })
          // }
        })
      }
    },
    initData (row) {
      if (row.hasOwnProperty('Status')) {
        row.Status = row.Status || '1'
        row.Status = row.Status.toString()
      } else {
        this.$set(row, 'Status', '1')
      }
      if (row.hasOwnProperty('Level')) {
        row.Level = row.Level || '1'
        row.Level = row.Level.toString()
      } else {
        this.$set(row, 'Level', '1')
      }
      if (row.hasOwnProperty('Stage')) {
        row.Stage = row.Stage || ''
        row.Stage = row.Stage.toString()
      }
      if (row.hasOwnProperty('Type') && row.Type === 0) {
        if (row.Type === 0) row.Type = ''
        else {
          row.Type = row.Type.toString()
        }
      }
      if (row.Started && row.Ended) {
        row.TaskDate = [row.Started, row.Ended]
      }
      if (row.Actualstarttime && row.Actualendtime) {
        row.Actual = [row.Actualstarttime, row.Actualendtime]
      }
    },
    getTaskById () {
      if (this.formData.id) {
        projectTaskApi.getPage({
          id: this.formData.Projectid,
          onetaskid: this.formData.id,
          planid: this.formData.Planid
        }).then(res => {
          if (res && res.length === 1) {
            for (let [key, value] of Object.entries(res[0])) {
              this.$set(this.formData, `${key}`, value)
            }
            this.initData(this.formData)
          }
        })
      } else {
        this.initData(this.formData)
      }
    },
    initDateTime () {
      let that = this
      let a = that.components.find(it => it.prop === 'TaskDate')
      if (a) {
        this.$set(a.attrs, 'picker-options', {
          disabledDate (time) {
            let w = new Date().valueOf() - 86400 * 1000
            if (that.formData.PlanStarted) {
              w = new Date(that.formData.PlanStarted).valueOf() - 86400 * 1000
            }
            return w > time.valueOf();
          }
        })
      }
    },
    initTaskDate () {
      let c = new Date().valueOf()
      let datas = [c, c + 86400 * 1000 * 3]
      if (this.formData.PlanStarted) {
        let p = new Date(this.formData.PlanStarted).valueOf()
        if (c < p) {
          datas = [p, p + 86400 * 1000 * 3]
        }
      }
      this.$set(this.formData, 'TaskDate', datas)
    }
  },
  watch: {
    dialogVisible (n, o) {
      console.log(JSON.parse(JSON.stringify(this.formData)))
      this.initDateTime()
      this.setComponents()
      this.getTaskById()
      if (!this.formData.Id) {
        this.initTaskDate()
      }
    }
  }
}